package com.lenovo.leos.filebrowser.ui;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity.OnTitleIconClickListener;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.XmlResourceParser;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.text.InputFilter;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.lenovo.leos.filebrowser.R;
import com.lenovo.leos.filebrowser.engine.util.DirDefines;
import com.lenovo.leos.filebrowser.engine.util.HzToPy;
import com.lenovo.leos.filebrowser.engine.util.MimeTypeParser;
import com.lenovo.leos.filebrowser.engine.util.MimeTypes;
import com.lenovo.leos.filebrowser.netdisk.FileSyncService;
import com.lenovo.leos.filebrowser.netdisk.FileSyncServiceManager;
import com.lenovo.leos.filebrowser.netdisk.SumTask;
import com.lenovo.leos.filebrowser.ui.IconifiedText;
import com.lenovo.leos.filebrowser.ui.FileInterfaceAdapter.ViewHolder;
import com.lenovo.leos.letools.db.FileUploadEntity;
import com.lenovo.leos.letools.exception.NetException;
import com.lenovo.leos.letools.exception.PreUploadException;
import com.lenovo.leos.letools.lenovodata.BaseNetClientServer;

public class FileInterface extends ListActivity implements
		OnTitleIconClickListener, FileFilter, OnTouchListener, OnClickListener {
	private static final String TAG = "FileInterface";
	private static final boolean TAG_FLAG = true;
	private static String saveFilePath;
//	private DownLoadServer mFileSyncService;// 下载任务管理器
//	private UploadServer mFileSyncService;// 上传文件
	private ArrayList<String> fileAndDirs = new ArrayList<String>();

	/*
	 * add 2010-11-13 by xie
	 */
	private class Position {
		private static final String TAG = "Postion";

		private File mfDir = null;
		private int miIndex = 0;

		public Position(int index, File file) {
			if (0 > index || null == file || !file.isDirectory()) {
				Log.e(TAG, "invalid parameter in Position");
				return;
			}
			miIndex = index;
			mfDir = file;
		}

		public void setIndex(int index) {
			if (0 > index) {
				Log.e(TAG, "invalid index in setIndex");
				return;
			} else
				miIndex = index;
		}

		public int getIndex() {
			return miIndex;
		}

		public void setDir(File file) {
			if (null == file || !file.isDirectory()) {
				Log.e(TAG, "invalid parameter in setPosY");
				return;
			} else
				mfDir = file;
		}

		public File getDir() {
			return mfDir;
		}

		public void dump() {
			if (TAG_FLAG) {
				Log.d(TAG, "===== Position Object Content =====");
				Log.d(TAG, "the index is: " + String.valueOf(miIndex));
				Log.d(TAG, "the dir is: " + mfDir.getAbsolutePath());
				Log.d(TAG, "===================================");
			}
		}
	};

	private static LinkedList<Position> sllPos = new LinkedList<Position>();
	private Position mpstCur = null;
	public static int State;
	public final static int _LIST = 10;
	public final static int _SELECT = 11;

	// end

	private enum DISPLAYMODE {
		ABSOLUTE, RELATIVE
	};

	private static String sdroot = Constant.sdroot;
	private final String root = Constant.sdroot;

	private enum LOCATION {
		LOCAL, SDCARD, UDISK
	};

	private final DISPLAYMODE displayMode = DISPLAYMODE.RELATIVE;
	private List<IconifiedText> directoryEntries = new ArrayList<IconifiedText>();;
	/** Dir separate for sorting */
	List<IconifiedText> mListDir = new ArrayList<IconifiedText>();
	/** Files separate for sorting */
	List<IconifiedText> mListFile = new ArrayList<IconifiedText>();
	/** SysDir separate for sorting */
	List<IconifiedText> mListSys = new ArrayList<IconifiedText>();
	private File currentDirectory = new File(sdroot);
	private Button btnSure, btnCancle;
	// private TabButtonTop btnLocal,btnSDcard;//,btnUdisk;
	private String selectFilePath = currentDirectory.getAbsolutePath();
	private ListView lv;
	private EditText et;
	private TextView tv;
	// private ImageButton ibnBack;
	Bundle bundle;
	Intent intent;
	// TabHost tabHost;
	private int requestCode = -1;// 0: select directory;1: save file;2:select
									// file
	private String mSelectedFile;
	private String mFileFilter = null;
	private String mDefaultPath;
	private IconifiedTextListAdapter itla = null;
	private FileInterfaceAdapter fileInterfaceAdapter = null;// add by xieqm
																// 110304

	final private int MODE_SELECT_FILE = 0;
	final private int MODE_SELECT_PATH = 1;
	final private int MODE_SAVE_FILE = 2;
	final private int LENOVO_MODE_SAVE_FILE = 3;// add by xieqm 110304
	final private int RAM_MODE_SAVE_FILE = 4;// add by xieqm 110316
	final private int RAM_MODE_SELECT_FILE = 5;// add by xieqm 110316
	final private int RAM_MODE_SELECT_PATH = 6;// add by xieqm 110316
	private boolean mRegisterReceiver = false;

	private static MimeTypes mMimeTypes = null;
	boolean mToCloseSend = false;
	public static final int FILE_NAME_NUM_MAX = 85;
	// add by xieqm 110304
	public static Button chooseBtn;
	public static List<File> MarkedFile = new ArrayList<File>();
	public static boolean isSelected = false;
	public static Button btnSelectAll;
	public static Button btnCancleAll;
	public static TextView uploadBtn;
	private static String selectState = "noSelect";
	private String mUpload, mDownload;
	private String[] netFileIds, netFileNames;
	private boolean[] netFileTypes;
	private String projectState;
	private String selectPath;
	private LinearLayout phoneLayout, sdcardLayout;
	private TextView sdcardText;
	private static int interfaceFlag = 55555555;
	private static String projectPath = DirDefines.mDir1;// 判断是什么存储设备 add by
															// xieqm 110317
	private final String ZIPENDSTRING = ".zip";
	static int count;
	private String uploadFileId;
	private String[] uploadFile;
	private boolean[] uploadFileTypes;
	// end
	
	FileSyncService mFileSyncService;

	

	private BroadcastReceiver SdCardIntentReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(intent.ACTION_MEDIA_UNMOUNTED)
					|| action.equals(Intent.ACTION_MEDIA_SHARED)) {
				// U MODE
				// context.getContentResolver().notifyChange(Uri.parse("content://mountstate"),
				// null);
				// SharedPreferences settings =
				// context.getSharedPreferences("U_MOUNT_STATE",
				// context.MODE_WORLD_READABLE);
				// settings.edit().putBoolean("MOUNT_STATE",false).commit();

				if (!mToCloseSend) {
					new AlertDialog.Builder(FileInterface.this)
							.setMessage(R.string.sd_shared)
							.setPositiveButton(R.string.alert_dialog_ok,
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int which) {
											finish();
										}
									}).show();
					mToCloseSend = true;
				}
			}
		}
	};

	/*
	 * add 2010-11-13 by xie
	 */
	private void initData() {
		if (null == sllPos) {
			sllPos = new LinkedList<Position>();
		} else
			sllPos.clear();
	}

	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);

		mFileSyncService = FileSyncServiceManager.getInstance(this).doBindService();
		
		projectState = getIntent().getStringExtra("projectState");
		mUpload = getIntent().getStringExtra("mUpload");
		mDownload = getIntent().getStringExtra("mDownload");
		netFileIds = getIntent().getStringArrayExtra("netFileIds");
		netFileNames = getIntent().getStringArrayExtra("netFileNames");
		netFileTypes = getIntent().getBooleanArrayExtra("netFileTypes");
		uploadFileId = getIntent().getStringExtra("uploadFileId");
//		mFileSyncService = new DownLoadServer(FileInterface.this);
		if (TAG_FLAG) {
			Log.d(TAG, "mUpload---------FileInterface------------" + mUpload);
			Log.d(TAG, "the uploadFileId is =============== " + uploadFileId);
			Log.d(TAG, "mDownload---------FileInterface------------"
					+ mDownload);
			if (null != netFileIds && null != netFileNames) {
				// Log.d(TAG, "the netFileIds is*****************"
				// + netFileIds.length);
				// Log.d(TAG, "the netFileNames is ***********************"
				// + netFileNames.length);
				Log.d(TAG, "the netFileTypes is ***********************"
						+ netFileTypes[0]);
			}
		}
		String status = Environment.getExternalStorageState();
		if (TAG_FLAG)
			Log.d(TAG, "!!!!!!!!!!!!!!!!!!!!!!!!!" + status);
		/*
		 * add 2010-11-13 by xie
		 */
		initData();
		if (status.equals(Environment.MEDIA_UNMOUNTED)) {// "unmounted"
			Toast.makeText(this, R.string.sd_unmounted, Toast.LENGTH_SHORT)
					.show();
			finish();
			return;
		} else if (status.equals(Environment.MEDIA_SHARED)) {
			Toast.makeText(this, R.string.sd_shared, Toast.LENGTH_SHORT).show();
			finish();
			return;
		} else if (status.equals(Environment.MEDIA_BAD_REMOVAL)) {
			Toast.makeText(this, R.string.sd_bad_removal, Toast.LENGTH_SHORT)
					.show();
			finish();
			return;
		} else if (status.equals(Environment.MEDIA_NOFS)) {
			Toast.makeText(this, R.string.sd_nofs, Toast.LENGTH_SHORT).show();
			finish();
			return;
		} else if (status.equals(Environment.MEDIA_CHECKING)) {// "checking"
			Toast.makeText(this, R.string.sd_disk_checking, Toast.LENGTH_SHORT)
					.show();
			finish();
			return;
		} else if (status.equals(Environment.MEDIA_UNMOUNTABLE)) {
			Toast.makeText(this, R.string.sd_corrupted, Toast.LENGTH_SHORT)
					.show();
			finish();
			return;
		}

		this.customTitleIcon(0, 0, 0, this);
		IntentFilter commandFilter = new IntentFilter();
		commandFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
		commandFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
		commandFilter.addAction(Intent.ACTION_MEDIA_REMOVED);
		commandFilter.addAction(Intent.ACTION_MEDIA_SHARED);
		commandFilter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);
		commandFilter.addAction(Intent.ACTION_MEDIA_EJECT);
		commandFilter.addDataScheme("file");
		registerReceiver(SdCardIntentReceiver, commandFilter);
		registerReceiver(sdCardIntentReceiver, commandFilter);// add by xieqm
																// 110317
		mRegisterReceiver = true;
		// directoryEntries = new ArrayList<IconifiedText>();//del by xieqm
		// 110304
		intent = this.getIntent();
		bundle = intent.getExtras();
		requestCode = bundle.getInt("request_code");
		mDefaultPath = bundle.getString("DEFAULT_PATH");
		if (TAG_FLAG) {
			Log.i(TAG,
					"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ mDefaultPath = "
							+ mDefaultPath);
			Log.i(TAG,
					"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ mcurrentPath = "
							+ selectFilePath);
		}
		if (mDefaultPath != null) {
			selectFilePath = mDefaultPath;
		}
		initMimeTypes();
		// end PH 091015
		if (TAG_FLAG) {
			Log.d(TAG,
					"projectPath@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ projectPath = "
							+ projectPath);
		}
		switch (requestCode) {
		case MODE_SELECT_FILE:
			if (projectPath.equals(DirDefines.mDir1)) {// add by xieqm 110317
				interfaceFlag = RAM_MODE_SELECT_FILE;
				setContentView(R.layout.td_select_interface);
				setTitle(R.string.fileselect);
				mFileFilter = bundle.getString("FILE_FILTER");
				phoneLayout = (LinearLayout) findViewById(R.id.phoneLayout);
				sdcardLayout = (LinearLayout) findViewById(R.id.sdcardLayout);
				sdcardText = (TextView) findViewById(R.id.sdcardText);
				phoneLayout.setOnTouchListener(this);
				sdcardLayout.setOnTouchListener(this);
				phoneLayout.setOnClickListener(this);
				sdcardLayout.setOnClickListener(this);
				if (status.equals(Environment.MEDIA_SHARED)
						|| status.equals(Environment.MEDIA_UNMOUNTED)
						|| status.equals(Environment.MEDIA_CHECKING)) {
					sdcardText.setTextColor(android.graphics.Color.GRAY);
					sdcardLayout.setEnabled(false);
				} else {
					sdcardText.setTextColor(android.graphics.Color.WHITE);
					sdcardLayout.setEnabled(true);
					sdcardLayout.setOnClickListener(this);
				}
				btnSure = (Button) this.findViewById(R.id.bnsure);
				btnCancle = (Button) this.findViewById(R.id.bncancle);
				lv = (ListView) this.getListView();
				lv.setOnItemClickListener(onItemClickListener);
				// lv.setOnItemSelectedListener(onItemSelectListener);
				tv = (TextView) findViewById(R.id.tvfileselect);
				setTitle(R.string.fileselect);
				LinearLayout linearLayout04 = (LinearLayout) this
						.findViewById(R.id.linearLayout03);
				linearLayout04.setVisibility(View.GONE);
				chooseBtn = (Button) findViewById(R.id.chooseBtn);// add by
																	// xieqm
																	// 110304
			} else if (projectPath.equals(DirDefines.mDir3)) {// end 110317
				selectFile();
			}
			break;
		// add by xieqm 110304
		case LENOVO_MODE_SAVE_FILE:
			mFileFilter = bundle.getString("FILE_FILTER");
			setContentView(R.layout.lenovo_fileselect);
			btnSure = (Button) this.findViewById(R.id.bnsure);
			btnCancle = (Button) this.findViewById(R.id.bncancle);
			lv = (ListView) this.getListView();
			lv.setOnItemClickListener(onItemClickListener);
			tv = (TextView) findViewById(R.id.tvfileselect);
			chooseBtn = (Button) findViewById(R.id.chooseBtn);
			setTitle(R.string.lenovo_upload);
			LinearLayout lenovoLayout = (LinearLayout) this
					.findViewById(R.id.TableLayout02);
			lenovoLayout.setVisibility(View.GONE);
			list();
			break;
		// end
		case MODE_SELECT_PATH:
			if (projectPath.equals(DirDefines.mDir1)) {// add by xieqm 110317
				interfaceFlag = RAM_MODE_SELECT_PATH;
				setContentView(R.layout.td_select_interface);
				if (TAG_FLAG) {
					Log.d(TAG, "MODE_SELECT_PATH====================" + mUpload
							+ "or===========" + mDownload);
				}
				if (mUpload != null || mDownload != null) {
					if (mDownload.equals(DirDefines.DOWNLOAD)) {
						setTitle(R.string.lenovo_download);
					} else {
						setTitle(R.string.pathselect);
					}
				} else {
					setTitle(R.string.pathselect);
				}
				mFileFilter = bundle.getString("FILE_FILTER");
				phoneLayout = (LinearLayout) findViewById(R.id.phoneLayout);
				sdcardLayout = (LinearLayout) findViewById(R.id.sdcardLayout);
				sdcardText = (TextView) findViewById(R.id.sdcardText);
				phoneLayout.setOnTouchListener(this);
				sdcardLayout.setOnTouchListener(this);
				phoneLayout.setOnClickListener(this);
				sdcardLayout.setOnClickListener(this);
				if (status.equals(Environment.MEDIA_SHARED)
						|| status.equals(Environment.MEDIA_UNMOUNTED)
						|| status.equals(Environment.MEDIA_CHECKING)) {
					sdcardText.setTextColor(android.graphics.Color.GRAY);
					sdcardLayout.setEnabled(false);
				} else {
					sdcardText.setTextColor(android.graphics.Color.WHITE);
					sdcardLayout.setEnabled(true);
					sdcardLayout.setOnClickListener(this);
				}
				LinearLayout linearLayout05 = (LinearLayout) this
						.findViewById(R.id.linearLayout03);
				linearLayout05.setVisibility(View.GONE);
				btnSure = (Button) this.findViewById(R.id.bnsure);
				btnCancle = (Button) this.findViewById(R.id.bncancle);
				lv = (ListView) this.getListView();
				lv.setOnItemClickListener(onItemClickListener);
				// lv.setOnItemSelectedListener(onItemSelectListener);
				tv = (TextView) findViewById(R.id.tvfileselect);
				mFileFilter = ".&784385jfkjskdji&*$((#*#()@)@)*(@#*";
				chooseBtn = (Button) findViewById(R.id.chooseBtn);// add by
																	// xieqm
																	// 110304
				list();
			} else if (projectPath.equals(DirDefines.mDir3)) {// end 110317
				selectPath();
			}
			break;
		case MODE_SAVE_FILE:
			if (projectPath.equals(DirDefines.mDir1)) {// add by xieqm 110317
				interfaceFlag = RAM_MODE_SAVE_FILE;
				setContentView(R.layout.td_save_interface);
				setTitle(R.string.savefiletitle);
				mFileFilter = bundle.getString("FILE_FILTER");
				phoneLayout = (LinearLayout) findViewById(R.id.phoneLayout);
				sdcardLayout = (LinearLayout) findViewById(R.id.sdcardLayout);
				sdcardText = (TextView) findViewById(R.id.sdcardText);
				phoneLayout.setOnTouchListener(this);
				sdcardLayout.setOnTouchListener(this);
				phoneLayout.setOnClickListener(this);
				sdcardLayout.setOnClickListener(this);
				if (status.equals(Environment.MEDIA_SHARED)
						|| status.equals(Environment.MEDIA_UNMOUNTED)
						|| status.equals(Environment.MEDIA_CHECKING)) {
					sdcardText.setTextColor(android.graphics.Color.GRAY);
					sdcardLayout.setEnabled(false);
				} else {
					sdcardText.setTextColor(android.graphics.Color.WHITE);
					sdcardLayout.setEnabled(true);
					sdcardLayout.setOnClickListener(this);
				}
				btnSure = (Button) this.findViewById(R.id.bnsure);
				btnCancle = (Button) this.findViewById(R.id.bncancle);
				LinearLayout linearLayout03 = (LinearLayout) this
						.findViewById(R.id.linearLayout03);
				linearLayout03.setVisibility(View.GONE);
				lv = (ListView) this.getListView();
				lv.setOnItemClickListener(onItemClickListener);
				// lv.setOnItemSelectedListener(onItemSelectListener);
				tv = (TextView) findViewById(R.id.tvfileselect);
				chooseBtn = (Button) findViewById(R.id.chooseBtn);// add by
																	// xieqm
																	// 110304
				list();
			} else if (projectPath.equals(DirDefines.mDir3)) {// end 110317
				saveFile();
			}
			break;
		case RAM_MODE_SELECT_FILE:
			selectFile();
			break;
		case RAM_MODE_SAVE_FILE:
			saveFile();
			break;
		case RAM_MODE_SELECT_PATH:
			selectPath();
			break;
		default:
			// Toast.makeText(FileInterface.this, "no request code",
			// Toast.LENGTH_LONG).show();
			finish();
		}
	}

	// add by xieqm 110318
	private void selectFile() {
		mFileFilter = bundle.getString("FILE_FILTER");
		setContentView(R.layout.fileselect);
		btnSure = (Button) this.findViewById(R.id.bnsure);
		btnCancle = (Button) this.findViewById(R.id.bncancle);
		lv = (ListView) this.getListView();
		lv.setOnItemClickListener(onItemClickListener);
		// lv.setOnItemSelectedListener(onItemSelectListener);
		tv = (TextView) findViewById(R.id.tvfileselect);
		setTitle(R.string.fileselect);
		LinearLayout layout = (LinearLayout) this
				.findViewById(R.id.TableLayout02);
		layout.setVisibility(View.GONE);
		chooseBtn = (Button) findViewById(R.id.chooseBtn);// add by xieqm
															// 110304
		list();
	}

	private void saveFile() {
		setContentView(R.layout.filesave);
		setTitle(R.string.savefiletitle);
		mFileFilter = bundle.getString("FILE_FILTER");
		btnSure = (Button) this.findViewById(R.id.bnsure);
		btnCancle = (Button) this.findViewById(R.id.bncancle);
		et = (EditText) this.findViewById(R.id.etinputname);
		et.setFilters(new InputFilter[] { new InputFilter.LengthFilter(
				FILE_NAME_NUM_MAX) });
		String defaultFileName = bundle.getString("DEFAULT_FILENAME");
		if (defaultFileName != null && (defaultFileName.length() > 0)) {
			if (isLong(defaultFileName)) {
				Toast.makeText(this, R.string.name_too_long, Toast.LENGTH_LONG)
						.show();
			} else {
				et.setText(defaultFileName);
			}
		}
		lv = (ListView) this.getListView();
		lv.setOnItemClickListener(onItemClickListener);
		// lv.setOnItemSelectedListener(onItemSelectListener);
		tv = (TextView) findViewById(R.id.tvfileselect);
		chooseBtn = (Button) findViewById(R.id.chooseBtn);// add by xieqm
															// 110304
		list();
	}

	private void selectPath() {
		setContentView(R.layout.fileselect);
		if (TAG_FLAG) {
			Log.d(TAG, "RAM_MODE_SELECT_PATH====================" + mUpload
					+ "or ============== " + mDownload);
		}
		if (mUpload != null || mDownload != null) {
			if (mDownload.equals(DirDefines.DOWNLOAD)) {
				setTitle(R.string.lenovo_download);
			} else {
				setTitle(R.string.pathselect);
			}
		} else {
			setTitle(R.string.pathselect);
		}
		btnSure = (Button) this.findViewById(R.id.bnsure);
		btnCancle = (Button) this.findViewById(R.id.bncancle);
		lv = (ListView) this.getListView();
		lv.setOnItemClickListener(onItemClickListener);
		// lv.setOnItemSelectedListener(onItemSelectListener);
		tv = (TextView) findViewById(R.id.tvfileselect);
		mFileFilter = ".&784385jfkjskdji&*$((#*#()@)@)*(@#*";
		chooseBtn = (Button) findViewById(R.id.chooseBtn);// add by xieqm
															// 110304
		list();
	}

	// end

	// add by xieqm 110316
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			phoneLayout
					.setBackgroundResource(android.R.drawable.list_selector_background);
			sdcardLayout
					.setBackgroundResource(android.R.drawable.list_selector_background);
		} else if (event.getAction() == MotionEvent.ACTION_UP) {
			phoneLayout.setBackgroundColor(0);
			sdcardLayout.setBackgroundColor(0);
		} else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
			phoneLayout.setBackgroundColor(0);
			sdcardLayout.setBackgroundColor(0);
		}
		return false;
	}

	// end

	@Override
	protected void onResume() {
		super.onResume();
		File currentDir = currentDirectory;
		if (!currentDirectory.exists()) {
			browseToRoot();
			new AlertDialog.Builder(this)
					.setMessage(
							currentDir.getName() + " "
									+ getString(R.string.dir_not_exist))
					.setPositiveButton(R.string.alert_dialog_ok,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {

								}
							}).show();

		} else {
			browseTo(currentDirectory);
		}

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		if (mRegisterReceiver) {
			unregisterReceiver(SdCardIntentReceiver);
			unregisterReceiver(sdCardIntentReceiver);
			if (TAG_FLAG)
				Log.i(TAG, "******OnDestroy unregisterReceiver *********");
		}
	}

	private void list() {
		if (TAG_FLAG)
			Log.d(TAG, "==>list" + selectState);

		if (mDefaultPath != null) {
			File path = new File(mDefaultPath);
			if (path.isDirectory()) {
				File localRoot = new File(this.sdroot);
				if (path.getAbsolutePath().equals(localRoot.getAbsolutePath()))
					browseTo(path);
				else
					browseTo(path);
				return;
			}
		}
		// browseTo(new File(sdroot));//del by xieqm 110314
		// add by xieqm 110314
		if (selectState != null) {
			if (selectState.equals(DirDefines.UPLOAD)) {
				browseTo(new File(selectFilePath));
			} else {
				browseTo(new File(sdroot));
			}
		} else {
			if (TAG_FLAG)
				Log.d(TAG, "==>list==>browseTo=======================");
			browseTo(new File(sdroot));
		}
		setBtnOnClick();// del by xieqm 110307
		// end
	}

	private void browseTo(final File file) {
		// If file is a directory,call fill() and browse it.
		if (TAG_FLAG)
			Log.d(TAG,
					"==>browseTo()----------------------"
							+ file.getAbsolutePath());
		saveFilePath = file.getAbsolutePath();
		if (file.isDirectory()) {
			this.currentDirectory = file;
			File localRoot = new File(sdroot);

			boolean bLocalRoot = false;
			if (localRoot.getAbsolutePath().equals(file.getAbsolutePath()))
				bLocalRoot = true;
			if (TAG_FLAG)
				Log.d(TAG, "==>mFileFilter----------------------" + bLocalRoot);
			if (this.mFileFilter != null) {
				fill(file.listFiles(this), bLocalRoot);
			} else
				fill(file.listFiles(), bLocalRoot);

			setLocationText(file.getPath());
		}
	}

	// add by PH 091016
	HashMap<String, Drawable> mMimeIconMap;

	private Drawable getDrawableForMimetype(String mimetype) {
		Drawable icon = null;
		if (mMimeIconMap == null) {
			mMimeIconMap = new HashMap<String, Drawable>();
		}

		icon = mMimeIconMap.get(mimetype);
		if (icon == null) {
			PackageManager pm = getPackageManager();
			Intent intent = new Intent(Intent.ACTION_VIEW);
			// intent.setType(mimetype);
			intent.setDataAndType(Uri.fromParts("file", "", null), mimetype);

			List<ResolveInfo> lri = pm.queryIntentActivities(intent,
					PackageManager.MATCH_DEFAULT_ONLY);
			List<ResolveInfo> lriRe = pm.queryBroadcastReceivers(intent,
					PackageManager.MATCH_DEFAULT_ONLY);
			if (lri != null && lri.size() > 0) {
				icon = lri.get(0).loadIcon(pm);
			} else if (lriRe != null && lriRe.size() > 0) {
				icon = lriRe.get(0).loadIcon(pm);
			}

			if (icon != null) {
				mMimeIconMap.put(mimetype, icon);
			} else {
				icon = getResources().getDrawable(R.drawable.icon_unknown_file);
				mMimeIconMap.put(mimetype, icon);
			}
		}

		return icon;
	}

	// end PH 091016

	// add by PH 091011
	private void initMimeTypes() {
		if (mMimeTypes == null) {
			MimeTypeParser mtp = new MimeTypeParser();

			// XmlResourceParser in =
			// getResources().getXml(com.android.internal.R.xml.mimetypes);
			XmlResourceParser in = getResources().getXml(R.xml.mimetypes);

			try {
				mMimeTypes = mtp.fromXmlResource(in);
			} catch (XmlPullParserException e) {
				Log.e("FileInterface",
						"PreselectedChannelsActivity: XmlPullParserException",
						e);
				throw new RuntimeException(
						"PreselectedChannelsActivity: XmlPullParserException");
			} catch (IOException e) {
				if (TAG_FLAG)
					Log.e("FileInterface",
							"PreselectedChannelsActivity: IOException", e);
				throw new RuntimeException(
						"PreselectedChannelsActivity(v.getId()) {: IOException");
			}
		}
	}

	private void addAllElements(List<IconifiedText> addTo,
			List<IconifiedText> addFrom) {
		int size = addFrom.size();
		for (int i = 0; i < size; i++) {
			addTo.add(addFrom.get(i));
		}
	}

	public static HzToPy mHz2Py = null;
	Comparator<IconifiedText> mSortWay = new Comparator<IconifiedText>() {
		public int compare(IconifiedText n1, IconifiedText n2) {
			int ret = 1;
			try {
				if (mHz2Py == null) {
					mHz2Py = new HzToPy(FileInterface.this);
				}

				int i = 0;
				String sChar1 = null, sChar2 = null;
				while (true) {
					String sPy1 = n1.getCharPy(i);
					String sPy2 = n2.getCharPy(i);

					if (sPy1 == null && sPy2 == null) {
						if (i < n1.getText().length())
							sChar1 = n1.getText().substring(i, i + 1);
						else
							return -1;

						if (i < n2.getText().length())
							sChar2 = n2.getText().substring(i, i + 1);
						else
							return 1;

						if (sChar2.equalsIgnoreCase(sChar1)) {
							String sPy = mHz2Py.Char2Py(sChar1.charAt(0));
							n1.appendPy(sPy);
							n2.appendPy(sPy);
							continue;
						} else {
							n1.appendPy(mHz2Py.Char2Py(sChar1.charAt(0)));
							n2.appendPy(mHz2Py.Char2Py(sChar2.charAt(0)));
							continue;
						}
					} else if (sPy1 == null) {
						if (i < n1.getText().length())
							sChar1 = n1.getText().substring(i, i + 1);
						else
							return -1;

						sChar2 = n2.getText().substring(i, i + 1);
						if (sChar2.equalsIgnoreCase(sChar1)) {
							n1.appendPy(n2.getCharPy(i));
							continue;
						} else {
							n1.appendPy(mHz2Py.Char2Py(sChar1.charAt(0)));
							continue;
						}
					} else if (sPy2 == null) {
						if (i < n2.getText().length())
							sChar2 = n2.getText().substring(i, i + 1);
						else
							return 1;

						sChar1 = n1.getText().substring(i, i + 1);
						if (sChar1.equalsIgnoreCase(sChar2)) {
							n2.appendPy(n1.getCharPy(i));
							continue;
						} else {
							n2.appendPy(mHz2Py.Char2Py(sChar2.charAt(0)));
							continue;
						}
					} else {
						int nRet = sPy1.compareTo(sPy2);
						if (nRet == 0) {
							i += 1;
							continue;
						}

						return nRet;
					}
				}
			} catch (IOException e) {
				Log.i(TAG,
						"**************catch a IOException in mHz2Py***************");
			}
			return ret;
		}
	};

	private void addIconifiedTextToList(IconifiedText item,
			List<IconifiedText> list) {
		int nIndex1 = 0;
		int nIndex2 = list.size() - 1;
		int nIndex = 0;
		if (nIndex2 < 0) {
			list.add(item);
			return;
		}

		while (true) {
			nIndex = (nIndex2 + nIndex1) / 2;
			IconifiedText temp = list.get(nIndex);

			int result = mSortWay.compare(item, temp);
			if (result > 0) {
				nIndex1 = nIndex + 1;
			} else if (result < 0) {
				nIndex2 = nIndex - 1;
			} else {
				list.add(nIndex, item);
				break;
			}

			if (nIndex1 > nIndex2) {
				if (result > 0) {
					if (nIndex >= list.size() - 1) {
						list.add(item);
					} else {
						list.add(nIndex + 1, item);
					}
				} else {
					list.add(nIndex, item);
				}

				break;
			}
		}
	}

	private void sortedFileList(File[] files) {
		if (files == null) {
			return;
		}

		Drawable currentSysIcon = getResources().getDrawable(
				R.drawable.icon_folder_sys);
		Drawable currentUsrIcon = getResources().getDrawable(
				R.drawable.icon_default_folder);
		Drawable fileIcon = null;

		this.mListDir.clear();
		this.mListFile.clear();
		this.mListSys.clear();

		for (File currentFile : files) {
			if (currentFile.isHidden()) {
				continue;
			}
			/*
			 * add 2010-11-4 xie
			 */
			if (currentFile.isDirectory()) {
				if (!Constant.isSysOrReservedDir(this, currentFile)
						&& !currentFile.getName().toUpperCase()
								.equals(Constant.invalidDir)) {
					// if (currentIcon == null)
					switch (this.displayMode) {
					case ABSOLUTE:
					case RELATIVE:
						addIconifiedTextToList(new IconifiedText(
								currentUsrIcon, currentFile, true), mListDir);
						break;
					}
				} else if (Constant.isSysOrReservedDir(this, currentFile)
						&& !currentFile.getName().toUpperCase()
								.equals(Constant.invalidDir)) {
					switch (this.displayMode) {
					case ABSOLUTE:
					case RELATIVE:
						addIconifiedTextToList(new IconifiedText(
								currentSysIcon, currentFile, true), mListSys);
						break;
					}
				}
			}
			// ////////////////////

			else {
				String fileName = currentFile.getName();
				// add by PH 091016
				String mimetype = mMimeTypes
						.getMimeType(fileName.toLowerCase());
				fileIcon = getDrawableForMimetype(mimetype);
				// add by xieqm 110318
				if (fileName.contains(ZIPENDSTRING)) {
					fileIcon = getResources().getDrawable(R.drawable.zip);
				}
				// end
				if (mimetype == null) {
					fileIcon = getResources().getDrawable(
							R.drawable.icon_unknown_file);
				}
				// end PH 091016

				switch (this.displayMode) {
				case ABSOLUTE:
				case RELATIVE:
					// this.directoryEntries.add(new
					// IconifiedText(fileIcon, currentFile, false));
					addIconifiedTextToList(new IconifiedText(fileIcon,
							currentFile, false), mListFile);
					break;
				}
			}
		}

	}

	private void fill(File[] files, boolean forLocalRoot) {
		if (TAG_FLAG) {
			Log.d(TAG, "==>fill------------------" + files.length);
			Log.d(TAG, "==>fill--------forLocalRoot----------" + forLocalRoot);
			Log.d(TAG, "==>fill--------selectState----------" + selectState);
		}
		this.directoryEntries.clear();

		sortedFileList(files);

		addAllElements(directoryEntries, mListSys);
		addAllElements(directoryEntries, mListDir);
		addAllElements(directoryEntries, mListFile);
		// add by xieqm 110304
		if (selectState.equals(DirDefines.UPLOAD)) {
			fileInterfaceAdapter = new FileInterfaceAdapter(this,
					directoryEntries);
			lv.setAdapter(fileInterfaceAdapter);
			selectState = "noSelect";
			if (TAG_FLAG)
				Log.d(TAG,
						"==>directoryEntries============="
								+ directoryEntries.size()
								+ "fileInterfaceAdapter======="
								+ fileInterfaceAdapter.getCount());
			count = fileInterfaceAdapter.getCount();
		} else {
			itla = new IconifiedTextListAdapter();
			lv.setAdapter(itla);
			if (TAG_FLAG)
				Log.d(TAG,
						"==>directoryEntries============="
								+ directoryEntries.size() + "itla======="
								+ itla.getCount());
			count = itla.getCount();
		}
		if (TAG_FLAG) {
			Log.d(TAG, "the itla.getCount()===============" + itla.getCount());
		}
		if (null != chooseBtn) {
			if (0 != itla.getCount()) {
				chooseBtn.setEnabled(true);
			} else {
				chooseBtn.setEnabled(false);
			}
		}
		// end
		// if (itla == null){
		// del by xieqm 110304
		// itla = new IconifiedTextListAdapter();
		// lv.setAdapter(itla);
		// end
		/*
		 * add 2010-11-13 by xie
		 */

		if (null != mpstCur) {
			File dir = mpstCur.getDir();
			mpstCur.dump();
			if (dir.equals(currentDirectory)) {
				lv.setSelection(mpstCur.getIndex());
			} else {
				lv.setSelection(0);
			}
		} else {
			lv.setSelection(0);
		}
	}

	// add by xieqm 110304
	private void initStates() {
		if (TAG_FLAG)
			Log.d(TAG, "==>initStates--- " + State);
		switch (State) {
		case _LIST:
			setContentView(R.layout.lenovo_fileselect);
			btnSure = (Button) this.findViewById(R.id.bnsure);
			btnCancle = (Button) this.findViewById(R.id.bncancle);
			lv = (ListView) this.getListView();
			lv.setOnItemClickListener(onItemClickListener);
			tv = (TextView) findViewById(R.id.tvfileselect);
			chooseBtn = (Button) findViewById(R.id.chooseBtn);
			setTitle(R.string.lenovo_upload);
			LinearLayout lenovoLayout = (LinearLayout) this
					.findViewById(R.id.TableLayout02);
			lenovoLayout.setVisibility(View.GONE);
			list();
			break;
		case _SELECT:
			if (!MarkedFile.isEmpty()) {
				MarkedFile.clear();
				isSelected = false;
			}
			uploadSelect();
			break;

		}
		// register a ContextMenu for the current listview
		lv.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				if (TAG_FLAG)
					Log.d(TAG, "==>setOnItemClickListener ");
				if (State == _LIST) {
					File clickedFile = null;
					switch (FileInterface.this.displayMode) {
					case RELATIVE:
						clickedFile = new File(
								FileInterface.this.currentDirectory
										.getAbsolutePath()
										+ "/"
										+ FileInterface.this.directoryEntries
												.get((int) arg3).getText());

						break;
					case ABSOLUTE:
						clickedFile = new File(
								FileInterface.this.directoryEntries.get(
										(int) arg3).getText());
						break;
					}
					if (clickedFile != null)
						if (clickedFile.isDirectory()) {
							if (State == _SELECT) {// add by PH 091102
								FileInterface.this.MarkedFile.clear();
								isSelected = false; // add by PH 091113
							}
						}
					Position pos = new Position(lv.getFirstVisiblePosition(),
							currentDirectory);
					pos.dump();
					sllPos.addFirst(pos);
					mpstCur = null;
					FileInterface.this.browseTo(clickedFile);
				} else {
					ViewHolder cache = (ViewHolder) arg1.getTag();
					cache.checkbox.setChecked(!cache.checkbox.isChecked());
				}
			}

		});

	}

	private void uploadSelect() {
		// TODO Auto-generated method stub
		if (TAG_FLAG)
			Log.d(TAG, "==>uploadSelect-----------" + selectFilePath);
		setContentView(R.layout.lenovo_upload_select);
		setTitle(R.string.upload);
		// TODO Auto-generated method stub
		btnSelectAll = (Button) findViewById(R.id.btnselectall);
		btnCancleAll = (Button) findViewById(R.id.btncancleall);
		btnCancleAll.setEnabled(false);
		uploadBtn = (TextView) findViewById(R.id.uploadBtn);
		uploadBtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				upload();
			}
		});
		btnSelectAll.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				markAllFile();
				// add by PH 091024
				btnCancleAll.setEnabled(true);
				btnSelectAll.setEnabled(false);
				// end PH 091024
			}
		});
		btnCancleAll.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// check all files in current directory
				unmarkallFile();
				// add by PH 091024
				btnCancleAll.setEnabled(false);
				btnSelectAll.setEnabled(true);
				// add by PH 091024
			}
		});
		lv = (ListView) findViewById(android.R.id.list);
		if (TAG_FLAG) {
			Log.d(TAG, "fileInterfaceAdapter======================"
					+ fileInterfaceAdapter);
		}
		lv.setAdapter(fileInterfaceAdapter);
	}

	private void upload() {
		new AlertDialog.Builder(FileInterface.this)
				.setTitle(R.string.upload)
				.setMessage(R.string.upload_detail)
				.setPositiveButton(R.string.alert_dialog_ok,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
								if (TAG_FLAG) {
									for (int i = 0; i < FileInterface.MarkedFile
											.size(); i++) {
										Log.d(TAG,
												"the FileInterface.MarkedFile=========="
														+ FileInterface.MarkedFile
																.get(i)
																.getAbsolutePath());
									}
								}
								uploadFile = new String[FileInterface.MarkedFile
										.size()];
								uploadFileTypes = new boolean[FileInterface.MarkedFile
										.size()];
								for (int i = 0; i < FileInterface.MarkedFile
										.size(); i++) {
									uploadFile[i] = FileInterface.MarkedFile
											.get(i).getAbsolutePath();
									uploadFileTypes[i] = FileInterface.MarkedFile
											.get(i).isDirectory();
								}
								final Intent intent = new Intent();
//								mFileSyncService = new UploadServer(
//										FileInterface.this);
								for (int i = 0; i < uploadFile.length; i++) {
									fileAndDirs.add(uploadFile[i]);//将上传文件夹的路径全称（文件夹所在路径+文件名）
									checkNum();
									File upFile = new File(uploadFile[i]);
									long fileSize = upFile.length();
									boolean isEnough = checkNetSpace(fileSize);
									if (isEnough) {
										return;
									}
									if (uploadFileTypes[i]) {
										if (TAG_FLAG) {
											Log.e(TAG, "start upload dir");
										}
										FileUploadEntity entity = mFileSyncService
												.getTaskByWholePath(uploadFile[i]);
										if (entity != null) {
											new AlertDialog.Builder(
													FileInterface.this)
													.setTitle(R.string.remind)
													.setMessage(R.string.ishave)
													.setPositiveButton(
															R.string.dlg_btn_ok,
															new DialogInterface.OnClickListener() {

																@Override
																public void onClick(
																		DialogInterface dialog,
																		int which) {
																	intent.setClass(
																			FileInterface.this,
																			com.lenovo.leos.filebrowser.netdisk.TaskManagerActivity.class);
																	startActivity(intent);
																	finish();
																}
															})
													.setNegativeButton(
															R.string.alert_dialog_cancel,
															new DialogInterface.OnClickListener() {

																@Override
																public void onClick(
																		DialogInterface dialog,
																		int which) {
																}

															}).show();
											return;
										}
										try {
											mFileSyncService
													.createDirTask(
															uploadFile[i],
															uploadFileId);
										} catch (NetException e) {
											new AlertDialog.Builder(
													FileInterface.this)
													.setTitle(R.string.remind)
													.setMessage(
															R.string.net_error)
													.setPositiveButton(
															R.string.dlg_btn_ok,
															new DialogInterface.OnClickListener() {

																@Override
																public void onClick(
																		DialogInterface dialog,
																		int which) {
																	finish();
																}
															}).show();
											return;
										} catch (PreUploadException e) {
											Toast.makeText(FileInterface.this,
													e.getMessage(),
													Toast.LENGTH_SHORT).show();
										}
									} else {
										if (TAG_FLAG) {
											Log.e(TAG, "start upload file");
										}
										FileUploadEntity entity = mFileSyncService
												.getTaskByWholePath(uploadFile[i]);
										if (entity != null) {
											new AlertDialog.Builder(
													FileInterface.this)
													.setTitle(R.string.remind)
													.setMessage(R.string.ishave)
													.setPositiveButton(
															R.string.dlg_btn_ok,
															new DialogInterface.OnClickListener() {

																@Override
																public void onClick(
																		DialogInterface dialog,
																		int which) {
																	intent.setClass(
																			FileInterface.this,
																			com.lenovo.leos.filebrowser.netdisk.TaskManagerActivity.class);
																	startActivity(intent);
																	finish();
																}
															})
													.setNegativeButton(
															R.string.alert_dialog_cancel,
															new DialogInterface.OnClickListener() {

																@Override
																public void onClick(
																		DialogInterface dialog,
																		int which) {
																}

															}).show();
											return;
										}
										// 创建任务
										try {
											mFileSyncService.createTask(
													uploadFile[i],
													uploadFileId, null, null);
										} catch (NetException e) {
											new AlertDialog.Builder(
													FileInterface.this)
													.setTitle(R.string.remind)
													.setMessage(
															R.string.net_error)
													.setPositiveButton(
															R.string.dlg_btn_ok,
															new DialogInterface.OnClickListener() {

																@Override
																public void onClick(
																		DialogInterface dialog,
																		int which) {
																	finish();
																}
															}).show();
											return;
										} catch (PreUploadException e) {
											Toast.makeText(FileInterface.this,
													e.getMessage(),
													Toast.LENGTH_SHORT).show();
										}
									}
								}

//								String mUpload = DirDefines.UPLOAD;
								intent.putExtra("projectState", projectState);
//								intent.putExtra("mUpload", mUpload);
								intent.putStringArrayListExtra("fileAndDirList", fileAndDirs);
								intent.setClass(
										FileInterface.this,
										com.lenovo.leos.filebrowser.netdisk.TaskManagerActivity.class);
								startActivity(intent);
								finish();
							}
						})
				.setNeutralButton(R.string.alert_dialog_cancel,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
							}
						}).show();
	}

	private void markAllFile() {
		// Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%markAllFile");
		MarkedFile.clear();
		for (int i = 0; i < directoryEntries.size(); i++) {
			if (!directoryEntries.get(i).getFile().isHidden()) {
				MarkedFile.add(directoryEntries.get(i).getFile());
			}
		}
		isSelected = true;
		fileInterfaceAdapter.notifyDataSetChanged();
	}

	private void unmarkallFile() {
		// Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%unmarkallFile");
		if (!MarkedFile.isEmpty()) {
			MarkedFile.clear();
			isSelected = false;

			fileInterfaceAdapter.notifyDataSetChanged();
		}
	}

	// end

	private void setBtnOnClick() {

		btnSure.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				if (mUpload != null || mDownload != null) {
					if (DirDefines.DOWNLOAD.equals(mDownload)) {
						final Intent intent = new Intent();
						if (DirDefines.mDir1.equals(projectState)) {
							intent.putExtra("projectState", DirDefines.mDir1);
						} else if (DirDefines.mDir3.equals(projectState)) {
							intent.putExtra("projectState", DirDefines.mDir3);
						}

						Log.e(TAG, "start task manager");
						if (null != netFileIds && null != netFileNames
								&& null != netFileTypes) {
							intent.putExtra("netFileIds", netFileIds);
							intent.putExtra("netFileNames", netFileNames);
							intent.putExtra("netFileTypes", netFileTypes);
						}

						try {
							// 创建一个文件夹下载任务
							for (int i = 0; i < netFileIds.length; i++) {
								checkNum();
								boolean isEnough = checkSdSpace(netFileIds[i]);
								if(isEnough){
									return;
								}
								fileAndDirs.add(netFileIds[i]);
								if (netFileTypes[i]) {
									if (TAG_FLAG) {
										Log.e(TAG, "the dir download");
									}
									mFileSyncService.createDirLoadTask(
											netFileIds[i], netFileNames[i],
											saveFilePath);
									intent.putExtra("dirid", netFileIds[i]);
								} else {
									if (TAG_FLAG) {
										Log.e(TAG, "the file download");
									}
									mFileSyncService.createFileLoadTask(
											netFileIds[i], saveFilePath, netFileNames[i]);
									intent.putExtra("dirid", netFileIds[i]);
								}
							}
						} catch (RuntimeException e) {
						    e.printStackTrace();
							new AlertDialog.Builder(FileInterface.this)
									.setTitle(R.string.remind)
									.setMessage(R.string.ishave)
									.setPositiveButton(
											R.string.dlg_btn_ok,
											new DialogInterface.OnClickListener() {

												@Override
												public void onClick(
														DialogInterface dialog,
														int which) {
													intent.setClass(
															FileInterface.this,
															com.lenovo.leos.filebrowser.netdisk.TaskManagerActivity.class);
													startActivity(intent);
													finish();
												}
											})
									.setNegativeButton(
											R.string.alert_dialog_cancel,
											new DialogInterface.OnClickListener() {

												@Override
												public void onClick(
														DialogInterface dialog,
														int which) {
												}

											}).show();
							return;
						} catch (NetException e) {
							new AlertDialog.Builder(FileInterface.this)
									.setTitle(R.string.remind)
									.setMessage(R.string.net_error)
									.setPositiveButton(
											R.string.dlg_btn_ok,
											new DialogInterface.OnClickListener() {

												@Override
												public void onClick(
														DialogInterface dialog,
														int which) {
													finish();
												}
											}).show();
							return;
						}
						// 当击这个文件后跳转到下载
//						mDownload = DirDefines.DOWNLOAD;
//						intent.putExtra("mDownload", mDownload);
//						intent.putExtra("saveFilePath", saveFilePath);
						intent.putStringArrayListExtra("fileAndDirList", fileAndDirs);
						intent.setClass(
								FileInterface.this,
								com.lenovo.leos.filebrowser.netdisk.TaskManagerActivity.class);
						startActivity(intent);
						finish();
					}
				} else {
					setResult();
				}
			}

		});
		btnCancle.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});
		// add by xieqm 110337
		if (chooseBtn != null) {
			chooseBtn.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					selectState = DirDefines.UPLOAD;
					list();
					State = _SELECT;
					initStates();
				}
			});
		}
		// end
	}

	private boolean checkisHave(String[] netFileNames, String saveFilePath) {
		boolean isHave = false;
		File file = new File(saveFilePath);
		File[] files = file.listRoots();
		String[] fileName = new String[files.length];
		for (int i = 0; i < files.length; i++) {
			fileName[i] = files[i].getName();

		}
		return isHave;
	}

	// private void checkDownloadNames(String[] netFileNames,
	// boolean[] netFileTypes, String saveFilePath) {
	// File file = new File(saveFilePath);
	// for (int i = 0; i < netFileNames.length; i++) {
	// if (netFileTypes[i] == true) {
	// }
	// }
	// }

	protected void onListItemClick(AdapterView<?> l, View v, int position,
			long id) {
		if (TAG_FLAG) {
			Log.e(TAG, "==> onListItemClick");
		}
		String selectedFileString = this.directoryEntries.get(position)
				.getText();
		if (TAG_FLAG)
			Log.d(TAG, "****************** onListItemClick "
					+ selectedFileString);
		/*
		 * add 2010-11-18 by xie
		 */
		Position pos = new Position(lv.getFirstVisiblePosition(),
				currentDirectory);
		sllPos.addFirst(pos);
		pos.dump();
		mpstCur = null;
		// end
		if (selectedFileString.equals(getString(R.string.current_dir))) {
			// Refresh
			browseTo(this.currentDirectory);

			selectFilePath = selectedFileString;
		} else if (selectedFileString.equals(getString(R.string.up_one_level))) {
			this.upOneLevel();
		} else {
			File clickedFile = null;
			if (TAG_FLAG)
				Log.i(TAG, "$$$$$$$$$$$$$$$$$$$$ displayMode=" + displayMode);
			switch (displayMode) {

			case RELATIVE:
				clickedFile = new File(currentDirectory.getAbsolutePath() + "/"
						+ selectedFileString);
				break;
			case ABSOLUTE:
				clickedFile = new File(selectedFileString);
				break;
			}
			if (clickedFile != null) {
				if (this.requestCode == MODE_SELECT_FILE) {
					mSelectedFile = clickedFile.getPath();
					setResult();
				} else if (requestCode == MODE_SAVE_FILE) {
					if (clickedFile.isFile())
						et.setText(selectedFileString);
				} else if (this.requestCode == RAM_MODE_SELECT_FILE) {// add by
																		// xieqm
																		// 110317
					mSelectedFile = clickedFile.getPath();
					setResult();
				} else if (this.requestCode == RAM_MODE_SAVE_FILE) {
					if (clickedFile.isFile())
						et.setText(selectedFileString);
				}// end
				if (clickedFile.isDirectory()) {
					selectFilePath = clickedFile.getAbsolutePath();
					browseTo(clickedFile);
				}
			}
		}
		selectPath = selectedFileString;// add by xieqm 110314
	}

	private void upOneLevel() {
		String parent = this.currentDirectory.getParent();
		if (parent != null) {
			if (parent.equals(root)) {
				parent = sdroot;
			}
			mpstCur = sllPos.poll();
			this.browseTo(new File(parent));
			selectFilePath = currentDirectory.getAbsolutePath();
		}
	}

	private OnItemClickListener onItemClickListener = new OnItemClickListener() {
		public void onItemClick(AdapterView<?> l, View v, int position, long id) {
			onListItemClick(l, v, position, id);
		}
	};

	private boolean isNameUseable(String name) {
		boolean ret = false;
		if (name.startsWith(".") == false && name.contains("/") == false
				&& name.contains("\\") == false && name.contains(":") == false
				&& name.contains("?") == false && name.contains("？") == false
				&& name.contains("<") == false && name.contains(">") == false
				&& name.contains("\"") == false && name.contains("|") == false
				&& name.contains("*") == false && name.contains("'") == false) {
			ret = true;
		}
		return ret;
	}

	/*
	 * add 2010-11-13 by xie
	 */
	private boolean isLong(String name) {
		boolean flag = false;
		int size = name.length();
		if (TAG_FLAG)
			Log.d(TAG, "**********size***********" + size);
		if (size > FILE_NAME_NUM_MAX)
			return true;
		return flag;
	}

	private void setResult() {
		// for file selection,if a directory is selected, open it when sure
		// button is pressed.

		if (requestCode == this.MODE_SELECT_FILE) {// update by xieqm 110317
			if (TAG_FLAG) {
				Log.d(TAG, "****************RESULT_OK : " + RESULT_OK);
			}
			File dir = new File(mSelectedFile);
			if (dir.isDirectory())
				browseTo(dir);
			else {
				bundle.putString("FILEPATH", mSelectedFile);
				if (TAG_FLAG)
					Log.d(TAG, "****************MODE_SELECT_FILE : "
							+ mSelectedFile);
				intent.putExtras(bundle);
				this.setResult(RESULT_OK, intent);
				finish();
			}
		}

		// add by xieqm 110304
		if (requestCode == this.LENOVO_MODE_SAVE_FILE) {
			File dir = new File(mSelectedFile);
			if (dir.isDirectory())
				browseTo(dir);
			else {
				bundle.putString("FILEPATH", mSelectedFile);
				if (TAG_FLAG)
					Log.d(TAG, "****************LENOVO_MODE_SAVE_FILE : "
							+ mSelectedFile);
				intent.putExtras(bundle);
				this.setResult(RESULT_OK, intent);
				finish();
			}
		}
		// end

		// for directory selection, if a file is selected, then get it's parent
		// path returned
		if (requestCode == this.MODE_SELECT_PATH
				|| requestCode == this.RAM_MODE_SELECT_PATH) {
			File dir = new File(selectFilePath);
			if (dir.isFile())
				selectFilePath = dir.getParent();
			bundle.putString("FILEPATH", selectFilePath);
			if (TAG_FLAG)
				Log.d(TAG, "****************MODE_SELECT_PATH_path : "
						+ selectFilePath);
			intent.putExtras(bundle);
			this.setResult(RESULT_OK, intent);
			finish();
		}

		if (requestCode == this.MODE_SAVE_FILE
				|| requestCode == this.RAM_MODE_SAVE_FILE) {
			final String fileName = et.getText().toString();
			final Intent myIntent = new Intent();
			// final Bundle myBundle = new Bundle();
			File tmp = new File(selectFilePath + "/" + fileName);

			if (fileName.trim().length() == 0) {
				Toast.makeText(this, R.string.nameempty, Toast.LENGTH_LONG)
						.show();
				return;
			} else if (!isNameUseable(fileName)) {
				Toast.makeText(this, R.string.namebad, Toast.LENGTH_LONG)
						.show();
				return;
			}

			if (tmp.exists()) {
				new AlertDialog.Builder(this)
						.setTitle(R.string.alert)
						.setMessage(R.string.override_interface)
						.setPositiveButton(R.string.alert_dialog_ok,
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dia,
											int which) {
										myIntent.putExtra("OVERRIDE", true);// override
																			// old
																			// file
										myIntent.putExtra("FILEPATH",
												selectFilePath + "/" + fileName);
										setResult(RESULT_OK, myIntent);// download
										finish();
									}
								}).show();

			} else {
				myIntent.putExtra("FILEPATH", selectFilePath + "/" + fileName);
				myIntent.putExtra("OVERRIDE", false);// override old file
				if (TAG_FLAG)
					Log.i(TAG, "*************** MODE_SAVE_FILE_path = "
							+ selectFilePath + "/" + fileName);
				setResult(RESULT_OK, myIntent);// download
				finish();
			}

		}
	}

	private OnItemSelectedListener onItemSelectListener = new OnItemSelectedListener() {

		public void onItemSelected(AdapterView<?> parent, View view,
				int position, long id) {
			onListItemSelect(parent, view, position, id);
		}

		public void onNothingSelected(AdapterView<?> parent) {
			// selectFilePath = currentDirectory.getAbsolutePath();
		}
	};

	protected void onListItemSelect(AdapterView<?> l, View v, int position,
			long id) {
		if (TAG_FLAG)
			Log.i(TAG, "##################### onListItemSelect");
		if (directoryEntries.get(position).getText().equals(".."))
			selectFilePath = currentDirectory.getAbsolutePath();
		else
			selectFilePath = currentDirectory.getAbsolutePath()
					+ directoryEntries.get(position).getText();

		if (requestCode == this.MODE_SAVE_FILE) {
			if (new File(selectFilePath).isFile())
				setLocationText(new File(selectFilePath).getParent());
		} else
			setLocationText(selectFilePath);
		// for file save, if a file is selected, set it's filename to input box
		// when it is selected
		if (requestCode == this.MODE_SELECT_PATH) {
			File file = new File(selectFilePath);
			if (file.isFile()) {
				et.setText(file.getName());
				selectFilePath = file.getParent();
			}
		}
		if (TAG_FLAG)
			Log.i(TAG, "################### selectFilePath= " + selectFilePath);
	}

	/**
	 * This function browses to the root-directory of the file-system.
	 */
	private void browseToRoot() {
		browseTo(new File(sdroot));
	}

	private void setLocationText(String lt) {
		// String relativePath = "";
		// String[] strArr;
		// String ln = "";
		// lt = Constant.textConvert(this, lt);
		// relativePath = lt.replaceFirst(Constant.sdroot,
		// getString(R.string.sdcard));
		// tv.setText(relativePath);
		String relativePath = "";
		String[] strArr;
		String ln = "";
		String result = "";
		lt = Constant.textConvert(this, lt);
		relativePath = lt.replaceFirst(DirDefines.mDir1,
				getString(R.string.sdcard));// Constant.sdroot
		relativePath = relativePath.trim();
		strArr = relativePath.split("/");
		for (int i = 1; i < strArr.length; i++) {
			ln += ">" + strArr[i];
		}
		result = getString(R.string.sdcard) + ln;
		// int index = result.lastIndexOf(">");
		// if (result.length() > 40) {
		// result = "......" + result.substring(index, result.length());
		tv.setText(result);
		// } else {
		// if (result.equals(getString(R.string.sdcard))) {
		// tv.setText(result + ">");
		// } else {
		// tv.setText(result);
		// }
		// }
	}

	public void onTitleIconClick() {
		// TODO Auto-generated method stub
		String parent = this.currentDirectory.getAbsolutePath();
		Log.d(TAG, "the parent is " + parent);
		Log.d(TAG, "the root is " + root);
		if (parent != null && !parent.equals(root) && State != _SELECT) {
			upOneLevel();
		} else if (parent != null && parent.equals(root) && State != _SELECT) {
			Log.d(TAG, " FileInterface quit fm");
			finish();
		} else if (State == _SELECT) {// add by xieqm 110337
			if (TAG_FLAG)
				Log.d(TAG, "$$$$$$$$$$$$$$$$$$$$$$$" + selectFilePath);
			finish();
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK: {
			onTitleIconClick();
			return true;
		}
		}
		return super.onKeyDown(keyCode, event);
	}

	public boolean accept(File pathname) {
		// TODO Auto-generated method stub
		if (pathname.isDirectory())
			return true;

		if (pathname.isFile()) {
			String sName = pathname.getAbsolutePath();
			int dotIndex = sName.lastIndexOf(".");
			String sExtend = sName.substring(dotIndex + 1);
			if (mFileFilter.toLowerCase().contains(sExtend.toLowerCase())) {
				return true;
			} else {
				return false;
			}
		}
		return false;
	}

	private class IconifiedTextListAdapter extends BaseAdapter {

		/** Remember our context so we can use it when constructing views. */
		private LayoutInflater mInflater;

		public IconifiedTextListAdapter() {
			mInflater = LayoutInflater.from(FileInterface.this);
		}

		/** @return The number of items in the */
		public int getCount() {
			if (TAG_FLAG)
				Log.v("TAG", "fileselect directoryEntries.size():"
						+ directoryEntries.size());
			return (directoryEntries == null) ? 0 : directoryEntries.size();
		}

		public Object getItem(int position) {
			return directoryEntries.get(position);
		}

		public boolean areAllItemsSelectable() {
			return false;
		}

		/** Use the array index as a unique id. */
		public long getItemId(int position) {
			return position;
		}

		/**
		 * @param convertView
		 *            The old view to overwrite, if one is passed
		 * @returns a IconifiedTextView that holds wraps around an IconifiedText
		 */
		public View getView(int position, View convertView, ViewGroup parent) {
			// IconifiedTextView btv;
			ViewHolder holder;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.fileselectlistitem,
						null);
				holder = new ViewHolder();
				holder.icon = (ImageView) convertView.findViewById(R.id.icon);
				holder.text = (TextView) convertView.findViewById(R.id.text);

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			String s;
			if (directoryEntries.get(position).isSysDir())
				s = Constant.textConvert(FileInterface.this, directoryEntries
						.get(position).getText());
			else
				s = directoryEntries.get(position).getText();

			if (s.startsWith("/")) {
				s = s.replaceFirst("/", "");
			}
			holder.text.setText(s);

			holder.icon.setImageDrawable(directoryEntries.get(position)
					.getIcon());
			return convertView;
		}

		class ViewHolder {
			ImageView icon;
			TextView text;
		}
	}

	// add by xieqm 110316
	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		Intent intent = new Intent();
		String OPEN_SAVE = "android.intent.action.OPEN_SAVE_DIALOG";
		switch (view.getId()) {
		case R.id.phoneLayout:
			if (interfaceFlag == RAM_MODE_SAVE_FILE) {
				saveFile();
			} else if (interfaceFlag == RAM_MODE_SELECT_FILE) {
				selectFile();
			} else if (interfaceFlag == RAM_MODE_SELECT_PATH) {
				selectPath();
			}
			break;
		case R.id.sdcardLayout:
			if (interfaceFlag == RAM_MODE_SAVE_FILE) {
				saveFile();
			} else if (interfaceFlag == RAM_MODE_SELECT_FILE) {
				selectFile();
			} else if (interfaceFlag == RAM_MODE_SELECT_PATH) {
				selectPath();
			}
			break;
		}
	}

	private BroadcastReceiver sdCardIntentReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (TAG_FLAG)
				Log.d(TAG, "#################### SDaction = " + action);
			if (action.equals(Intent.ACTION_MEDIA_SHARED)
					|| action.equals(Intent.ACTION_MEDIA_UNMOUNTABLE)
					|| action.equals(Intent.ACTION_MEDIA_UNMOUNTED)
					|| action.equals(Intent.ACTION_MEDIA_BAD_REMOVAL)
					|| action.equals(Intent.ACTION_MEDIA_NOFS)
					|| action.equals(Intent.ACTION_MEDIA_CHECKING)
					|| action.equals(Intent.ACTION_MEDIA_REMOVED)) {
				sdcardText.setTextColor(android.graphics.Color.GRAY);
				sdcardLayout.setEnabled(false);
			} else {
				sdcardText.setTextColor(android.graphics.Color.WHITE);
				sdcardLayout.setEnabled(true);
				sdcardLayout.setOnClickListener(FileInterface.this);
			}
		}
	};

	// end

	/**
	 * 超过20个任务弹出提示
	 */
	private void checkNum() {
		SumTask.getInstance().setContext(FileInterface.this);
		int sumTask = SumTask.getInstance().getSumTask();
		if (sumTask == SumTask.NUM) {
			Toast.makeText(FileInterface.this, R.string.task_full,
					Toast.LENGTH_SHORT).show();
			return;
		}
	}

	/**
	 * 检测空间是否足够
	 */
	private boolean checkNetSpace(long fileSize) {
		boolean isEnough = false;
		long netfreeSpace = 0;
		String state = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(state)) {
			netfreeSpace = SumTask.getInstance().getNetFreeSpace();
		}
		if (fileSize > netfreeSpace) {
			Toast.makeText(FileInterface.this,
					getString(R.string.net_insufficient_space),
					Toast.LENGTH_SHORT).show();
			isEnough = true;
		}
		return isEnough;
	}
	
	/**
	 * 检测空间是否足够
	 */
	private boolean checkSdSpace(String netFileId) {
		boolean isEnough = false;
		long sdfreeSpace = 0;
		BaseNetClientServer baseClient = new BaseNetClientServer();
		List<String> retVal = null;
		try {
			retVal = baseClient.predownload(FileInterface.this, netFileId);
			if(retVal == null) return true;
			String fileLen = "0";//文件长度
			long fileSize = 0;
			//取得文件长度和原始名称
			for (String cookieVal : retVal) {
				if (cookieVal.contains("FILELENGTH")) {
					fileLen = cookieVal.substring(cookieVal.indexOf("=") + 1);
					fileSize = Long.valueOf(fileLen);
				}
			}
			String state = Environment.getExternalStorageState();
			if (Environment.MEDIA_MOUNTED.equals(state)) {
				File sdcardDir = Environment.getExternalStorageDirectory();
				StatFs sf = new StatFs(sdcardDir.getPath());
				long blockSize = sf.getBlockSize();
				long availCount = sf.getAvailableBlocks();
				sdfreeSpace = blockSize * availCount;
			}
			if (fileSize > sdfreeSpace) {
				Toast.makeText(FileInterface.this,
						getString(R.string.nospaceonsd),
						Toast.LENGTH_SHORT).show();
				isEnough = true;
			}
		} catch (NetException e) {
			e.printStackTrace();
		}
		
		return isEnough;
	}
	
	/**
	 * 下载时检测本地是否有同名文件
	 * @param netFileId
	 * @param fileName
	 * @param savePath
	 * @return
	 */
	private boolean isSameFile(final String netFileId, final String fileName, final String savePath){
		boolean isSame = true;
		File file = new File(savePath);
		File[] files = file.listFiles();
		for(int i=0;i<files.length;i++){
			if(fileName.equals(files[i].getName())){
				new AlertDialog.Builder(FileInterface.this)
				.setTitle(R.string.remind)
				.setMessage(R.string.isSame)
				.setPositiveButton(
						R.string.dlg_btn_ok,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(
									DialogInterface dialog,
									int which) {
								try {
									mFileSyncService.createDirLoadTask(
											netFileId, fileName,
											savePath);
								} catch (NetException e) {
									e.printStackTrace();
									new AlertDialog.Builder(FileInterface.this)
									.setTitle(R.string.remind)
									.setMessage(R.string.net_error)
									.setPositiveButton(
											R.string.dlg_btn_ok,
											new DialogInterface.OnClickListener() {

												@Override
												public void onClick(
														DialogInterface dialog,
														int which) {
													finish();
												}
											}).show();
								}
								fileAndDirs.add(netFileId);
								intent.putExtra("dirid", netFileId);
								intent.putStringArrayListExtra("fileAndDirList", fileAndDirs);
								intent.setClass(
										FileInterface.this,
										com.lenovo.leos.filebrowser.netdisk.TaskManagerActivity.class);
								startActivity(intent);
								finish();
							}
						})
				.setNegativeButton(
						R.string.alert_dialog_cancel,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(
									DialogInterface dialog,
									int which) {
							}

						}).show();
			}
		}
		return isSame;
	}

}